package ashok.corejava.threads;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ThreadSynchronizedTwo {
	
	public static void main(String args[]){
		
		Worker work = new Worker();
		work.main();
	}
	
	
}

class Worker{
	
	
	private Object lock1 = new Object();
	public Object lock2 = new Object();
	private Random random = new Random();
	private List<Integer> list = new ArrayList<Integer>();
	private List<Integer> list1 = new ArrayList<Integer>();
	
	
	public  void stageOne(int thread){
		synchronized(lock1){
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("StageOne running...Of thread"+thread);
			list.add(random.nextInt());
		}
	}
	public  void stageTwo(int thread){
		synchronized(lock2){
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("StageTwo running...Of thread"+thread);
		list1.add(random.nextInt());
		}
	}
	
	public void process(int thread){
		for(int i=0;i<1000;i++){
			stageOne(thread);
			stageTwo(thread);
		}
	}
	public void main(){
		
		System.out.println("Starting");
		long start = System.currentTimeMillis();
		Thread t1 = new Thread(new Runnable()
		{
			public void run(){
			process(1);
		}
		});	
		t1.start();
		
		Thread t2 = new Thread(new Runnable()
		{
			public void run(){
			process(2);
		}
		});	
		t2.start();
		
	
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	
		long end = System.currentTimeMillis();
		System.out.println("Time taken "+(end - start));
		System.out.println("List size"+list.size());
		System.out.println("List1 size"+list1.size());
		
	}
}